package com.gmh.service.impl;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import com.gmh.dto.Result;
import com.gmh.entity.Shop;
import com.gmh.mapper.ShopMapper;
import com.gmh.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gmh.utils.CacheClient;
import com.gmh.utils.SystemConstants;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.gmh.utils.RedisConstants.*;


@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    private RedissonClient redissonClient;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheClient cacheClient;

    @Resource
    private ShopMapper shopMapper; // 注入 ShopMapper

    private static BloomFilter<Long> bloomFilter;  // 布隆过滤器声明

    @PostConstruct //  初始化布隆过滤器
    public void initBloomFilter() {
        // 1. 从数据库加载所有店铺 ID
        List<Long> shopIds = this.getAllShopIdsFromDatabase();

        // 2. 创建布隆过滤器
        bloomFilter = BloomFilter.create(
                Funnels.longFunnel(), // 使用 Long 类型
                shopIds.size(),        // 期望插入的元素数量
                0.01                      // 误判率 (1%)
        );

        // 3. 将店铺 ID 添加到布隆过滤器
        for (Long shopId : shopIds) {
            bloomFilter.put(shopId);
        }
    }

    // 获取所有店铺 ID
    private List<Long> getAllShopIdsFromDatabase() {
        return shopMapper.selectList(null).stream().map(Shop::getId).collect(Collectors.toList());
    }

    @Override
    public Result queryById(Long id) {
        // 布隆过滤器判断数据是否存在
        if (!bloomFilter.mightContain(id)) {
            return Result.fail("布隆过滤器拦截错误请求");
        }

        String key = CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        // 如果缓存中存在数据，直接返回
        if (StrUtil.isNotBlank(shopJson)) {
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return Result.ok(shop);
        }

        // 使用 Redisson 的分布式锁防止多个请求同时访问数据库
        String lockKey = LOCK_SHOP_KEY + id;
        RLock lock = redissonClient.getLock(lockKey);

        boolean isLockAcquired = false;
        try {
            // 尝试获取分布式锁，最多等待 10 秒，锁持有 30 秒
            isLockAcquired = lock.tryLock(LOCK_SHOP_TTL, 30, TimeUnit.SECONDS);

            if (!isLockAcquired) {
                // 如果没有获取到锁，则返回失败
                return Result.fail("请求过于频繁，请稍后再试");
            }

            // 再次检查缓存（防止在获取锁的过程中缓存已经被其他请求加载）
            shopJson = stringRedisTemplate.opsForValue().get(key);
            if (StrUtil.isNotBlank(shopJson)) {
                Shop shop = JSONUtil.toBean(shopJson, Shop.class);
                return Result.ok(shop);
            }

            // 访问数据库获取数据
            Shop shop = getById(id);
            if (shop == null) {
                return Result.fail("店铺不存在");
            }

            // 更新缓存，设置过期时间
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL + RandomUtil.randomInt(1, 30), TimeUnit.MINUTES);
            return Result.ok(shop);

        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return Result.fail("请求失败，请稍后再试");
        } finally {
            // 释放锁
            if (isLockAcquired) {
                lock.unlock();
            }
        }
    }

    @Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (id == null){
            return Result.fail("id不能为空");
        }
        //1.更新数据库
        updateById(shop);
        //2.删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
        //3.返回
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        //1.判断是否需要根据坐标查询
        if (x == null || y == null){
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            return Result.ok(page.getRecords());
        }
        //2.计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;

        //3.查询redis，根据类型分页查询
        String key = SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo()
                .search(
                        key,
                        GeoReference.fromCoordinate(x, y),
                        new Distance(5000),
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end)
                );
        //4.查询数据库，解析id
        if (results == null){
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent(); // 获取所有结果
        if (list.size() <= from){
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = new ArrayList<>();
        Map<String, Distance> distanceMap = new HashMap<>();
        list.stream().skip(from).forEach( result -> {
            String shopIdstr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdstr));
            distanceMap.put(shopIdstr, result.getDistance());
        });

        String idstr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + idstr + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        //5.返回
        return Result.ok(shops);
    }
}
